import React, { useState, useEffect, useRef } from "react"
import styled from "styled-components"
import { useNavigate } from "react-router-dom"
import { host, allUsersRoute } from "../utils/APIRoutes"
import { ToastContainer, toast } from "react-toastify"
import Contacts from "../components/Contacts"
import Welcome from "../components/Welcome"
import ChatContainer from "../components/ChatContainer"
import axios from "axios"
import { io } from "socket.io-client"

export default function Chat() {
  const socket = useRef()
  const navigate = useNavigate()

  const [contacts, setContacts] = useState([])
  const [currentUser, setCurrentUser] = useState(undefined)
  const [currentChat, setCurrentChat] = useState(undefined)

  const toastOptions = {
    position: "bottom-right",
    autoClose: 5000,
    pauseOnHover: true,
    draggable: true,
    hideProgressBar: true,
    theme: "dark",
  }

  useEffect(() => {
    if (!localStorage.getItem("snappy-user")) {
      navigate("/login")
    } else {
      setCurrentUser(JSON.parse(localStorage.getItem("snappy-user")))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (currentUser) {
      socket.current = io(host)
      socket.current.emit("add-user", currentUser._id)
    }
  }, [currentUser])

  useEffect(() => {
    if (currentUser) {
      if (currentUser.isAvatarImageSet) {
        axios
          .get(`${allUsersRoute}/${currentUser._id}`)
          .then((res) => {
            if (res.data.status) {
              setContacts(res.data.users)
            } else {
              toast.error("Cannot find the user.", toastOptions)
            }
          })
          .catch(() => {
            toast.error("Unknown error.", toastOptions)
          })
      } else {
        navigate("/setAvatar")
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentUser])

  const handleChatChange = (chat) => {
    setCurrentChat(chat)
  }

  return (
    <>
      <Container>
        <div className="container">
          <Contacts
            contacts={contacts}
            currentUser={currentUser}
            changeChat={handleChatChange}
          />
          {currentChat ? (
            <ChatContainer
              currentChat={currentChat}
              currentUser={currentUser}
              socket={socket}
            />
          ) : (
            <Welcome currentUser={currentUser} />
          )}
        </div>
      </Container>
      <ToastContainer />
    </>
  )
}

const Container = styled.div`
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 1rem;
  background-color: #131324;
  .container {
    height: 85vh;
    width: 85vw;
    background-color: #00000076;
    display: grid;
    grid-template-columns: 25% 75%;
    @media screen and (min-width: 720px) and (max-width: 1080px) {
      grid-template-columns: 35% 65%;
    }
  }
`
